﻿using System;
using System.Collections;
using System.Threading;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation;
using Microsoft.SPOT.Presentation.Controls;
using Microsoft.SPOT.Presentation.Media;
using Microsoft.SPOT.Touch;

using Gadgeteer.Networking;
using GT = Gadgeteer;
using GTM = Gadgeteer.Modules;
using Gadgeteer.Modules.GHIElectronics;

namespace BluetoothTest
{
    public partial class Program
    {
        // This method is run when the mainboard is powered up or reset.   
        void ProgramStarted()
        {
            bluetooth.SetDeviceName("Gadgeteer");
  
            bluetooth.BluetoothStateChanged += bluetooth_BluetoothStateChanged;
            bluetooth.DataReceived += bluetooth_DataReceived;
            bluetooth.DeviceInquired += bluetooth_DeviceInquired;

            bluetooth.HostMode.InquireDevice();

            //The timer gives the device enough time to initialize.
            Gadgeteer.Timer timer = new Gadgeteer.Timer(1000, Gadgeteer.Timer.BehaviorType.RunOnce);
            timer.Tick += timer_Tick;
            timer.Start();
        }

        void bluetooth_DeviceInquired(Bluetooth sender, string macAddress, string name)
        {
            
        }

        void timer_Tick(Gadgeteer.Timer timer)
        {
            //You only need to enter pairing mode once with a device. After you pair for the first time, it will
            //automatically connect in the future.
            if (!bluetooth.IsConnected)
                bluetooth.ClientMode.EnterPairingMode();
        }

        void bluetooth_BluetoothStateChanged(Bluetooth sender, Bluetooth.BluetoothState btState)
        {
            Debug.Print(btState.ToString());
        }

        void bluetooth_DataReceived(Bluetooth sender, string data)
        {
            Debug.Print(data);
            sender.ClientMode.SendLine(data); //echoes the data back to the device.
            sender.ClientMode.Disconnect();
        }
    }
}
